<?php

class HomepagePhotosController extends AppController {

  //public $scaffold;
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session', 'Util', 'Upload');
  public $name = 'HomepagePhotos';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'HomepagePhoto.created' => 'desc'
            ));
  }

//admin and public version
  function admin_index() {
    $this->layout = 'admin';
    $this->set('photos', $this->paginate('HomepagePhoto'));
  }

  function admin_add() {
    $this->layout = 'admin';
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }

  function admin_add_multiple() {
    $this->layout = 'admin';
    if ($this->request->is('post')) {
      $this->render('admin_invalid'); //handled in ImagesController
    }
  }

  //admin
  function admin_edit($id = null) {
    $this->layout = 'admin';
    //TODO - options have to be changed. We have the photo id here not the album id, the link  and possible category/album data will be incorrect
    $this->HomepagePhoto->id = $id;
    if ($this->request->is('get')) {
      $this->request->data = $this->HomepagePhoto->read();
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

  function admin_edit_ajax($id = null) {
    $this->layout = 'admin';
    $result = array();
    if ($this->request->is('post')) {
      $data = $this->request->data;
      $this->HomepagePhoto->id = $data['photoId'];
      $updateResult = $this->HomepagePhoto->save(array("HomepagePhoto" => array('caption' => $data['photoCaption'])), false, array('caption', 'modified_by'));
      if (!empty($updateResult)) {
        $result = array('success' => true, 'data' => $updateResult, 'id' => $data['photoId']);
      } else {
        $result = array('success' => false, 'message' => 'The record was not successfully update. Please try again.');
      }
    }
    $json = array('result' => $result);
    $this->set('json', $json);
    $this->render('/Elements/json', '/json/default');
  }

  private function _processAction($dataIn, $action='add', $id=null) {
    $this->layout = 'admin';
    $data = $this->_processRequestData($dataIn);
    $data["HomepagePhoto"]["image_path"] = $data["HomepagePhoto"]["photo_image_path"];
    $data["HomepagePhoto"]["caption"] = $data["HomepagePhoto"]["photo_caption"];
    if ($action === "add") {
      $this->HomepagePhoto->set($data);
      if ($this->HomepagePhoto->validates()) {
        if (!empty($data["HomepagePhoto"]["image_path"]) && !empty($data["HomepagePhoto"]["image_path"]['name'])) {
          $albumsFolder = Configure::read('App.homepageImageFolder');
          $fileName = $this->Util->cleanFileName($data["HomepagePhoto"]["image_path"]['name'], true) . "_" . date("U");
          $imageUploaded = $this->Upload->uploadImage($data["HomepagePhoto"]["image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $albumsFolder, Configure::read("App.homepageImageWidth"), null, $fileName, true, Configure::read('App.photoImageThumbWidth'));
          $data["HomepagePhoto"]["image_path"] = $albumsFolder . '/' . $imageUploaded;
          $data["HomepagePhoto"]["image_thumb_path"] = $albumsFolder . '/' . Configure::read('App.defaultThumbnailPrefix') . $imageUploaded;
        }
        if ($this->HomepagePhoto->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'admin' => true));
        }
      } else {
        $this->request->data['HomepagePhoto'] = $data['HomepagePhoto'];
        $this->set('errors', $this->Photo->validationErrors);
        $this->render('admin_add');
      }
    } elseif ($action === "edit") {
      $originalRec = $this->HomepagePhoto->find("first", array("conditions" => array("HomepagePhoto.id" => $id)));
      $this->HomepagePhoto->set($data);
      if ($this->HomepagePhoto->validates()) {
        //update record
        if ($this->HomepagePhoto->save($data, false, array('caption'))) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'admin' => true));
        }
      } else {
        $data['HomepagePhoto']['image_path'] = $originalRec["HomepagePhoto"]["image_path"];
        $data['HomepagePhoto']['id'] = $id;
        $this->request->data['HomepagePhoto'] = $data['HomepagePhoto'];
        $this->set('errors', $this->HomepagePhoto->validationErrors);
        $this->render('admin_edit');
      }
    }
  }

  function admin_delete($id) {
    $this->layout = 'admin';
    $this->deleteImage($id);
    if ($this->HomepagePhoto->delete($id)) {
      $this->Session->setFlash('The photo has been deleted.');
      $this->redirect(array('action' => 'index', 'admin' => true));
    }
  }

  function deleteImage($id) {
    $this->layout = 'admin';
    //TODO - Images are not being deleted
    $retVal = false;
    $image = $this->HomepagePhoto->read(array('image_path', 'image_thumb_path'), $id);
    $imagePath = $image['HomepagePhoto']['image_path'];
    $imageThumbPath = $image['HomepagePhoto']['image_thumb_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $resultThumb = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imageThumbPath);
      $retVal = $result && $resultThumb;
    }
    return $retVal;
  }

  function admin_invalid() {
    $this->layout = 'admin';
    //Throw 404 Exception
    throw new NotFoundException('The url that was entered was not valid');
  }

}

?>
